<?php
namespace app\api\controller;

use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;

class Collection extends Base
{
    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:显示收藏的店铺
     * @param:
     * @return json
     * @throws \think\exception\DbException
     */
    public function collectSupplier(){
        $data = Request::instance()->post();
        if (!empty($data['user_id'])&& array_key_exists('search',$data) && array_key_exists('type',$data)){
            if (!empty($data['page_no'])){
                $pageNo     = $data['page_no'];
                $pageSize   = 4;
            }
            $where  = [
                'S.name'         => ['like','%'.trim($data['search']).'%'],
                'U.is_del'       => 0,
                'U.user_id'      => $data['user_id'],
            ];
            if(!empty($data['typeSos'])){
                if (!empty($data['type'])){
                    $typeId = $data['type'];
                    $list = Db::table('user_collect')
                        ->alias('U')
                        ->field('S.id as supplier_id, S.name as supplier_name, S.image, S.business, S.is_open, S.star')
                        ->join('supplier S','S.id = U.supplier_id')
                        ->where($where)
                        ->where("FIND_IN_SET($typeId,S.business)")
                        ->order('U.collect_time desc')
                        ->paginate(12,false,['path'=>'javascript:ajaxPage([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page']);
                }else{
                    $list = Db::table('user_collect')
                        ->alias('U')
                        ->field('S.id as supplier_id, S.name as supplier_name, S.image, S.business, S.is_open, S.star')
                        ->join('supplier S','S.id = U.supplier_id')
                        ->where($where)
                        ->order('U.collect_time desc')
                        ->paginate(12,false,['path'=>'javascript:ajaxPage([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page']);
                }
                $collect = $list->toArray();
                if ($collect){
                    $result = Config::get('code.success');
                    $result['html']         = $list->render();
                    $result['collect']      = $collect;
                }else{
                    $result = Config::get('code.null');
                }
            }else{
                $collect['list'] = Db::table('user_collect')
                    ->alias('U')
                    ->field('S.id as supplier_id, S.name as supplier_name, S.image, S.business, S.is_open, S.star')
                    ->join('supplier S','S.id = U.supplier_id')
                    ->where($where)
                    ->limit(($pageNo-1)*$pageSize,$pageSize)
                    ->order('U.collect_time desc')
                    ->select();
                if (!empty($data['type'])){
                    foreach ($collect['list'] as $k=>$v){
                        $business =explode(',',$v['business']);
                        if (!in_array($data['type'],$business)){
                            unset($collect['list'][$k]);
                        }
                    }
                }
                if ($collect['list']){
                    $result = Config::get('code.success');
                    $result['collect']  = $collect;
                }else{
                    $result = Config::get('code.null');
                }
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-19
     * @description:收藏店铺
     * @param:
     * @return json
     */
    public function confirmCollectSupplier(){
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && !empty($data['supplier_id'])){
            $info['user_id']        = $data['user_id'];
            $info['supplier_id']    = $data['supplier_id'];
            $info['is_del']         = 0;
            $info['collect_time']   = date("Y-m-d H:i:s",time());
            $info['flag']           = 1;
            $count = Db::table('user_collect')
                ->where(['user_id' => $info['user_id'], 'supplier_id' => $info['supplier_id'], 'is_del' => 0])
                ->count();
            if ($count > 0){
                $result['status'] = 209;
                $result['msg']    = '已收藏该商家';
                return json($result);
            }
            $res = Db::table('user_collect')->insert($info);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:显示收藏的商品
     * @param:
     * @return json
     */
    public function collectProduct(){
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && array_key_exists('type',$data) &&  array_key_exists('page_no',$data)){
            $pageNo     = $data['page_no'];
            $pageSize   = 4;
            if ($data['type'] == '-1'){ //失效
                $where  = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'P.is_shelves' => ['<>',1], 'Ps.is_default' => 1];
            }elseif ($data['type'] == '0'){ //全部
                $where  = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'Ps.is_default' => 1];
            }elseif ($data['type'] == '1'){ // 六个月前,
                $time   = gainTime('month','-6');
                $year   = date('Y',$time);
                $month  = date('m',$time);
                $where  = [
                    'U.user_id'     => $data['user_id'],
                    'U.is_del'      => 0,
                    'U.year'        => ['<=',$year],
                    'U.month'       => ['<=',$month],
                    'P.is_shelves'  => ['<>',1],
                    'Ps.is_default' => 1
                ];
            }elseif ($data['type'] == '2'){ // 一年前,
                $time   = gainTime('month','-12');
                $year   = date('Y',$time);
                $where  = [
                    'U.user_id'     => $data['user_id'],
                    'U.is_del'      => 0,
                    'U.year'        => ['<=',$year],
                    'P.is_shelves'  => ['<>',1],
                    'Ps.is_default' => 1
                ];
            }else{
                return json(Config::get('code.mistake'));
            }
            if(!empty($data['typeSos'])){
                $list = Db::name('user_collect_product')
                    ->alias('U')
                    ->field('U.id as collect_id, P.id as product_id, P.name as product_name,Ps.price, Ps.packing_proportion, Ps.unit, Ps.specification, P.is_shelves, P.image,P.supplier')
                    ->join('product_specification Ps','Ps.product_id = U.product_id','left')
                    ->join('product P','P.id = U.product_id','left')
                    ->where($where)
                    ->order('U.collect_time desc')
                    ->group('U.id')
                    ->paginate(12,false,['path'=>'javascript:ajaxPage([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page_no']);
                $collect = $list->toArray();
                if ($collect){
                    foreach ($collect['data'] as $k=>$v){
                        $collect['data'][$k]['price'] = number_format($v['price'],2,'.','');
                    }
                    $result = Config::get('code.success');
                    $result['paginate']     = $list->render();
                    $result['collect']      = $collect;
                }else{
                    $result = Config::get('code.null');
                }
            }else{
                $collect['list'] = Db::table('user_collect_product')
                    ->alias('U')
                    ->field('U.id as collect_id, P.id as product_id, P.name as product_name, Ps.price, Ps.packing_proportion, Ps.unit, Ps.specification, P.image, P.is_shelves')
                    ->join('product_specification Ps','Ps.product_id = U.product_id')
                    ->join('product P','P.id = U.product_id')
                    ->where($where)
//                    ->limit(($pageNo-1)*$pageSize,$pageSize)
                    ->order('U.collect_time desc')
                    ->select();
                $collect['count']       = count($collect['list']);
                $collect['total_count'] = Db::table('user_collect_product')
                    ->alias('U')
                    ->join('product_specification Ps','Ps.product_id = U.product_id')
                    ->join('product P','P.id = U.product_id')
                    ->where($where)
                    ->count();
                $count = Db::table('user_collect_product')
                    ->alias('U')
                    ->join('product_specification Ps','Ps.product_id = U.product_id')
                    ->join('product P','P.id = U.product_id')
                    ->where(['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'Ps.is_default' => 1, 'P.is_shelves' => ['<>',1]])
                    ->count();
                if ($collect['list']){
                    foreach ($collect['list'] as $k=>$v){
                        $collect['list'][$k]['price'] = number_format($v['price'],2,'.','');
                    }
                    $result = Config::get('code.success');
                    $result['collect']          = $collect;
                    $result['overdue_count']    = $count;
                }else{
                    $result = Config::get('code.null');
                }
            }

        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-19
     * @rewriter:
     * @rewriter_date:
     * @description:收藏商品
     * @param:
     * @return json
     */
    public function confirmCollectProduct(){
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && !empty($data['product_id'])){
            $info['user_id']        = $data['user_id'];
            $info['product_id']     = $data['product_id'];
            $info['is_del']         = 0;
            $info['collect_time']   = date("Y-m-d H:i:s",time());
            $info['flag']           = 1;
            $time   = timeCompute(time());
            $info   = array_merge($time,$info);
            $count = Db::table('user_collect_product')
                ->where(['user_id' => $info['user_id'], 'product_id' => $info['product_id'], 'is_del' => 0])
                ->count();
            if ($count > 0){
                $result['status'] = 209;
                $result['msg']    = '已收藏该商品';
                return json($result);
            }
            $res = Db::table('user_collect_product')->insert($info);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:删除失效收藏商品
     * @param:
     * @return json
     */
    public function delCollect(){
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && array_key_exists('type', $data)){
            if ($data['type'] == '-1'){ //失效
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'P.is_shelves' => ['<>',1]];
            }elseif ($data['type'] == '0'){ //全部
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0];
            }else{
                return json(Config::get('code.mistake'));
            }
            $res = Db::table('user_collect_product')
                ->alias('U')
                ->join('product P','P.id = U.product_id')
                ->where($where)
                ->setField('U.is_del', 1);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description:批量删除收藏商品
     * @param:
     * @return json
     */
    public function delCollectProduct(){
        $data = Request::instance()->post();
        if (!empty($data['id'])){
            $data['id'] = trim($data['id'],',');
            $collect_id = explode(',',$data['id']);
            foreach ($collect_id as $k=>$v){
                $res = Db::table('user_collect_product')
                    ->where('id',$v)
                    ->setField('is_del', 1);
            }
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-02
     * @rewriter:
     * @rewriter_date:
     * @description:取消收藏商品
     * @param:
     * @return json
     */
    public function delProduct(){
        $data = Request::instance()->post();
        if (!empty($data['product_id'])&&!empty($data['user_id'])){
            $res = Db::table('user_collect_product')
                ->where(['user_id'=>$data['user_id'],'product_id'=>$data['product_id']])
                ->setField('is_del', 1);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description:收藏商家分类
     * @param:
     * @return json
     */
    public function CollectClassify(){
        $classify['list'] = Db::table('base_data')
            ->field('id, name, name_english')
            ->where(['level'=>0,'type_menu'=>1,'flag'=>1])
            ->select();
        $classify['count'] = count($classify['list']);
        if ($classify){
            $result = Config::get('code.success');
            $result['classify'] = $classify;
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }

}
